package fr.liglab.adele.icasa.rooms;

import java.text.DecimalFormat;
import java.text.NumberFormat;

import org.apache.felix.ipojo.annotations.Component;
import org.apache.felix.ipojo.annotations.Invalidate;
import org.apache.felix.ipojo.annotations.Provides;
import org.apache.felix.ipojo.annotations.Requires;
import org.apache.felix.ipojo.annotations.ServiceProperty;
import org.apache.felix.ipojo.annotations.Validate;

import fr.liglab.adele.icasa.device.DeviceListener;
import fr.liglab.adele.icasa.device.light.DimmerLight;
import fr.liglab.adele.icasa.device.light.Photometer;
import fr.liglab.adele.icasa.device.temperature.Cooler;
import fr.liglab.adele.icasa.device.temperature.Heater;
import fr.liglab.adele.icasa.device.temperature.Thermometer;
import fr.liglab.adele.icasa.environment.SimulatedEnvironment;
import fr.liglab.adele.icasa.environment.SimulatedEnvironmentManager;
import fr.liglab.adele.icasa.interfaces.IBedroom;

@Component
@Provides
public class Bedroom implements DeviceListener, IBedroom{

	@Requires
	Photometer photometer;
	
	@Requires
	DimmerLight dimmerlight;
	
	@Requires(filter="(environment.id=envBedroom)")
	SimulatedEnvironment env;
	
	@Requires
	SimulatedEnvironmentManager env_manager;
	
	double targetIlluminance;
	
	@Validate
	public void starting() {
		env_manager.bindDeviceToEnvironment("photometer", "envBedroom");
		env_manager.bindDeviceToEnvironment("dimmerlight", "envBedroom");
		
		photometer.addListener(this);
		
		if (targetIlluminance>100 || targetIlluminance<0)
			System.out.println( " <Bedroom> Target illuminance invalid ("+targetIlluminance+"). It should be a value between 0 and 100.");
		
		System.out.println( " ---------> Bedroom ACTIVE <--------- " );
	}
	
	@Invalidate
	public void stopping() {    
		System.out.println( " ---------> Bedroom INACTIVE <--------- " );
	}

	public void notifyDeviceEvent() {
		NumberFormat formatter = new DecimalFormat("#0.00");
		double currentIlluminance = photometer.getIlluminance();
		double illumDimmer=dimmerlight.getPowerLevel();

		System.out.println(
							" <Bedroom> current illuminance=" + formatter.format(currentIlluminance)	+ " target=" + formatter.format(targetIlluminance) 
							+ " dimmer_power="+formatter.format(illumDimmer));
		
		if (currentIlluminance < targetIlluminance) { 
			if (illumDimmer<=0.9)
				dimmerlight.setPowerLevel(illumDimmer + 0.1);
		} else if (currentIlluminance > targetIlluminance) {
			if (illumDimmer>=0.1)
				dimmerlight.setPowerLevel(illumDimmer - 0.1);
		}else {
			System.out.println(" <Bedroom> dimmer stay in the same illuminance");
		}
	}

	public void setTargetIlluminance(double newvalue){
		targetIlluminance=newvalue;
	}

	
	
}
